# XBMC Video add-on for WatchTREK (allstepisodes.com)
# created by Ludolphus, december 2010, ludolphus@gmail.com
# The Star Trek episodes are not hosted by me, but on the site mentioned.
# This script just does some website scraping to make the episodes viewable in XBMC
import urllib,urllib2,re,sys,xbmcplugin,xbmcgui,xbmcaddon

HEADER = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.6.3'

def CATEGORIES():
		addDir('The Original Series - Season 1','http://www.allstepisodes.com/series/TOS/tosbase1.php',1,'http://rimworlds.com/theclassicsciencefictionchannel/wp-content/uploads/2009/05/startrekoriginalseries.jpg')
		addDir('The Original Series - Season 2','http://www.allstepisodes.com/series/TOS/tosbase2.php',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/tos_nav.png')
		addDir('The Original Series - Season 3','http://www.allstepisodes.com/series/TOS/tosbase3.php',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/tos_nav.png')
		addDir('Next Generation - Season 1','http://www.allstepisodes.com/series/TNG/next_gen_base1.php',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/tng_nav.png')
		addDir('Next Generation - Season 2','http://www.allstepisodes.com/series/TNG/next_gen_base2.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/tng_nav.png')
		addDir('Next Generation - Season 3','http://www.allstepisodes.com/series/TNG/next_gen_base3.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/tng_nav.png')
		addDir('Next Generation - Season 4','http://www.allstepisodes.com/series/TNG/next_gen_base4.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/tng_nav.png')
		addDir('Next Generation - Season 5','http://www.allstepisodes.com/series/TNG/next_gen_base5.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/tng_nav.png')
		addDir('Next Generation - Season 6','http://www.allstepisodes.com/series/TNG/next_gen_base6.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/tng_nav.png')
		addDir('Next Generation - Season 7','http://www.allstepisodes.com/series/TNG/next_gen_base7.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/tng_nav.png')
		addDir('Deep Space Nine - Season 1','http://www.allstepisodes.com/series/DS9/ds9_base1.php',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ds9_nav.png')
		addDir('Deep Space Nine - Season 2','http://www.allstepisodes.com/series/DS9/ds9_base2.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ds9_nav.png')
		addDir('Deep Space Nine - Season 3','http://www.allstepisodes.com/series/DS9/ds9_base3.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ds9_nav.png')
		addDir('Deep Space Nine - Season 4','http://www.allstepisodes.com/series/DS9/ds9_base4.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ds9_nav.png')
		addDir('Deep Space Nine - Season 5','http://www.allstepisodes.com/series/DS9/ds9_base5.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ds9_nav.png')
		addDir('Deep Space Nine - Season 6','http://www.allstepisodes.com/series/DS9/ds9_base6.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ds9_nav.png')
		addDir('Deep Space Nine - Season 7','http://www.allstepisodes.com/series/DS9/ds9_base7.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ds9_nav.png')
		addDir('Voyager - Season 1','http://www.allstepisodes.com/series/VOY/voyager_base1.php',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/voy_nav.png')
		addDir('Voyager - Season 2','http://www.allstepisodes.com/series/VOY/voyager_base2.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/voy_nav.png')
		addDir('Voyager - Season 3','http://www.allstepisodes.com/series/VOY/voyager_base3.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/voy_nav.png')
		addDir('Voyager - Season 4','http://www.allstepisodes.com/series/VOY/voyager_base4.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/voy_nav.png')
		addDir('Voyager - Season 5','http://www.allstepisodes.com/series/VOY/voyager_base5.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/voy_nav.png')
		addDir('Voyager - Season 6','http://www.allstepisodes.com/series/VOY/voyager_base6.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/voy_nav.png')
		addDir('Voyager - Season 7','http://www.allstepisodes.com/series/VOY/voyager_base7.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/voy_nav.png')
		addDir('Enterprise - Season 1','http://www.allstepisodes.com/series/ENT/enterprise_base1.php',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ent_nav.png')
		addDir('Enterprise - Season 2','http://www.allstepisodes.com/series/ENT/enterprise_base2.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ent_nav.png')
		addDir('Enterprise - Season 3','http://www.allstepisodes.com/series/ENT/enterprise_base3.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ent_nav.png')
		addDir('Enterprise - Season 4','http://www.allstepisodes.com/series/ENT/enterprise_base4.html',1,'http://i931.photobucket.com/albums/ad153/bagodeism1/homepage/ent_nav.png')

def INDEX(url):
    req = urllib2.Request(url)
    req.add_header('User-Agent', HEADER)
    response = urllib2.urlopen(req)
    link=response.read()
    response.close()

    thumbs=re.compile('<div class="thumbnailer">\n(\s*?)<a href="(.+?)">(\s*?)<img src="(.+?)"(.+?)/></a>').findall(link)
    match=re.compile('<div class="episode_description">\n(\s*?)<h2> \n(\s*?)<a href="(.+?)">(.+?)</a>').findall(link)
    index=0
    for p,q,videourl,name in match:
        addLink(name,videourl,2,'','',thumbs[index][3])
        index = index + 1

def VIDEOLINKS(url):
    req = urllib2.Request(url)
    req.addheaders = [('Referer', 'http://allstepisodes.com/'),
			('Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)')]
    response = urllib2.urlopen(req)
    link=response.read()
    response.close()

    match=re.compile('<meta http-equiv="refresh" content="2;url=(.+?)"><center>').findall(link)
    if (len(match)>0):
        url=match[0]
        req = urllib2.Request(url)
        req.addheaders = [('Referer', 'http://allstepisodes.com/'),
			('Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)')]
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()

    match=re.compile("<embed src='http://www.4shared.com/flash/player.swf\?ver=10226&file=(.+?)'").findall(link)
    if (len(match)<1):
        match=re.compile("so.addVariable\('file','(.+?)'\);").findall(link)
    if (len(match)<1):
        #more scraping
        temp=re.compile("<iframe width='900' height='530' frameborder='0' src='(.+?)'").findall(link)
        if (len(temp)>0):
            url=temp[0]
            req = urllib2.Request(url)
            req.add_header('User-Agent', HEADER)
            response = urllib2.urlopen(req)
            link=response.read()
            response.close()
            match=re.compile('flashvars.file="(.+?)";').findall(link)
            if (len(match)<1):
                return #giving up for now
        else:
            return #giving up for now
    url=match[0]
    play=xbmc.Player().play(url)
                
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param

def addLink(name,url,mode,date,desc,iconimage):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
	description = desc + "\n \n Published: " + date
	liz.setInfo( type="Video", infoLabels={ "Title": name,"Plot":description,"Date": date } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)
	return ok

def addLinkOld(name,url,desc,date,iconimage):
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        description = desc + "\n \n Published: " + date
        liz.setInfo( type="Video", infoLabels={ "Title": name,"Plot":description,"Date": date } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
        return ok


def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok


params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

print 'Mode',str(mode)
print 'URL: ',str(url)
print 'Name: ',str(name)

if mode==None or url==None or len(url)<1:
        print ("")
        CATEGORIES()
       
elif mode==1:
        print ""+url
        INDEX(url)
        
elif mode==2:
	print ""+url
	VIDEOLINKS(url)

xbmcplugin.endOfDirectory(int(sys.argv[1]))
